const Koa = require("koa");
const Router = require("koa-router");
const static = require("koa-static");
const jwt = require("jsonwebtoken");
const parser = require("koa-bodyparser");
const { exec } = require("./db");
const key = "wang";

const app = new Koa();
const router = new Router();

app.use(static(__dirname + "/views"))
app.use(parser())

// 登录
router.post("/login",async (ctx) => {
    const {userName,password} = ctx.request.body;
    // 在数据库中匹配
    const data = await exec(`select * from user where userName="${userName}" and password="${password}"`)
    console.log(data)
    if(data.length > 0){
        const token = jwt.sign({
            userName:data[0].userName,
            userId:data[0].userId,
        },key,{
            expiresIn:"1h"
        })
        ctx.body = {
            message:"登陆成功",
            token
        }
    }else{
        ctx.body = {
            message:'账号密码不匹配'
        }
    }
})

app.use(router.routes());

app.listen(4444,() => {
    console.log("127.0.0.1:4444");
})